package admin

import (
	"fmt"
	"net/http"
	"runtime"
	"time"

	"enterprise-base/internal/models"
	"enterprise-base/internal/utils"

	"github.com/gin-gonic/gin"
)

func TestHandler(c *gin.Context) {
	c.Set("no_auth", true)
	// 获取操作系统名称
	osName := runtime.GOOS
	// 获取架构信息
	osArch := runtime.GOARCH
	// 构建响应
	response := gin.H{
		"os_name": osName,
		"os_arch": osArch,
	}
	utils.RedisSetExpireKey(c, "test", "1111212", 10*60*time.Second)
	val, _ := utils.RedisGetKey(c, "test")
	fmt.Println(*val)
	models.ApiSuccess(c, response)
}

func Add(c *gin.Context) {
	var admin Admin
	admin.Name = "name"
	admin.CreateAt = time.Now().Unix()
	admin.UpdateAt = time.Now().Unix()
	sql := "INSERT INTO test (name,create_at,update_at) VALUES ($1, $2, $3)"
	row, err := utils.DbExecuteSQL(sql, admin.Name, admin.CreateAt, admin.UpdateAt)
	if err != nil {
		models.ApiError(c, err)
		c.Abort()
		return
	}
	models.ApiSuccess(c, row)
}

func Update(c *gin.Context) {
	var admin Admin
	admin.ID = 2
	admin.Name = "name"
	// 创建时间 10位时间戳
	admin.UpdateAt = time.Now().Unix()
	sql := "UPDATE test SET name=$1, update_at=$2 WHERE id=$3"
	row, err := utils.DbExecuteSQL(sql, admin.Name, admin.UpdateAt, admin.ID)
	if err != nil {
		models.ApiError(c, err)
		c.Abort()
		return
	}
	models.ApiSuccess(c, row)
}

func Get(c *gin.Context) {
	var admin Admin
	err := utils.DbGet(&admin, "SELECT * FROM test WHERE id = $1", 1)
	if err != nil {
		fmt.Println("err", err)
		models.ApiError(c, err)
		c.Abort()
		return
	}

	c.JSON(http.StatusOK, admin)
}

func Select(c *gin.Context) {
	var admins []Admin
	err := utils.DbSelect(&admins, "SELECT * FROM test WHERE id = $1", 1)
	if err != nil {
		fmt.Println("err", err)
		models.ApiError(c, err)
		c.Abort()
		return
	}

	c.JSON(http.StatusOK, admins)
}
